layui.define(['element', 'api', 'fast_config', 'domain_design_business', 'amis', 'utils'], function(exports) {
	"use strict";

	/**
	 * Button component
	 * */
	var MOD_NAME = 'domain_design_vo',
		$ = layui.jquery,
        api = layui.api,
        fast_config = layui.fast_config,
        domain_design_business = layui.domain_design_business,
        listeners = layui.listener,
        utils = layui.utils,
        amis = layui.amis
    ;

	var domain_design_vo = function(opt) {
		this.option = opt;
	};

	function saveDesign(option){
        var grid_domain_vo_fields = option.grid_domain_design_business.option.grid.getData();
        var formObject = {};

        let fieldNames=[];
        for(var field of grid_domain_vo_fields){
            fieldNames.push(field["fieldName"]);
            var validation=[];
            if(field["Keyword"]){
                validation.push("Keyword");
            }
            if(field["Repeat"]){
                validation.push("Repeat");
            }
            if(field["NotEmpty"]){
                validation.push("NotEmpty");
            }
            field["validationTypeList"] = validation;
        }

        formObject["fieldList"] = grid_domain_vo_fields;
        formObject["scope"] = "app";
        formObject["modelType"] = "vo";

        const newListLength=new Set(fieldNames.map(item=>item)).size;
        const listLength=fieldNames.length;

        if(listLength>newListLength){
            layer.alert('字段英文名不可重复，请调整后保存。');
        }else if(grid_domain_vo_fields.length<1){
            layer.alert('请先设计字段！');
        }else{
            var optionApi = {
                enableRootPath:true,
                type: "POST",
                url: fast_config.moudle.domain.saveApi.format({nodeid:option.treeNode.id}),
                data: JSON.stringify(formObject),
                contentType : 'application/json;charset=UTF-8',
                success: function(data){
                    layer.msg('操作成功');
                    if(option.callback && option.callback.reloadtree && typeof option.callback.reloadtree === 'function'){
                        option.callback.reloadtree(data);
                    }
                }
            };

            api.exec(optionApi)
        }
    }

    function getModelData(option){
        var modelJson=null;
        var optionApi = {
            enableRootPath:true,
            type: "GET",
            url: fast_config.moudle.domain.initApi.format({nodeid:option.treeNode.id}),
            success: function(data){
                if(typeof data !== 'object' ){
                    modelJson =  JSON.parse(data);
                }
            }
        };

        api.exec(optionApi);

        return modelJson;
    }

    function appendElem(option){

        //debugger
        var id = option.treeNode.tId;
        var domainContainerId = 'domainContainer_' + id;
        var saveId = "saveDesignVo_" + id;

        var domainContainer = `
            <div id="${domainContainerId}">
                <div class="layui-tab layui-tab-brief" lay-filter="docDemoTabBrief">
                    <ul class="layui-tab-title domainTabs">
                        <li class="layui-this">基础字段</li>
                    </ul>
                    <div class="layui-tab-content" id="domainVoContent">
                        <div class="layui-tab-item item-pgGride layui-show" >
                            <div class="padding10 ">
                                <div id="${getDomainVoFields(option)}"></div>
                            </div>
                        </div>
                    </div>
            
            </div>
		`;

        $(option.elem).append(domainContainer);

        // <span class="buttonBox">
        //     <button id="${saveId}" type="button" class="layui-btn layui-btn-primary layui-btn-xs domainSave"> <span>保存</span></button>
        // </span>

        // $('#' + saveId).click(function(){
        //     saveDesign(option);
        // });
    }

    function getDomainVoFields(option){
        var id = option.treeNode.tId;
        return 'domainVoFields_' + id;
    }

    /**
	 * Button start loading
	 * */
    domain_design_vo.prototype.render = function(opt) {
		
		var option = {
			elem: opt.elem,
            data: opt.data,
            treeNode: opt.treeNode,
            viewMode: opt.viewMode,
            pearBody : opt.pearBody,
            amisData: opt.amisData,
            callback: opt.callback,
            grid_domain_design_business: null
		}

        render(option);

        /**
         * 保存值对象型监听器
         * 该监听器在资源工具栏中使用
         * @param {} event
         * @param {*} spanSchema
         * @param {*} toolbrObj
         */
        function saveDomainVoResourceToolbarListener(event, spanSchema, toolbrObj){
            //当data.id有值则会选中id节点，没有则只刷新
            saveDesign(option);
        }

        /**
         * 模块装配
         */
        listeners.registerToolbarListener("saveDomainVoResourceToolbarListener", saveDomainVoResourceToolbarListener)

        return new domain_design_vo(option);
	}

    function render(option){

        appendElem(option);
        var id = option.treeNode.tId;
        var modelJson = getModelData(option);
        // debugger

        var initVoFields;
        if(modelJson !=null){
            initVoFields = modelJson.fieldList;
        }

        // grid;
        option.grid_domain_design_business = domain_design_business.render({
            elem: '#' + getDomainVoFields(option),
            initData: initVoFields
        });
    }

    exports(MOD_NAME, new domain_design_vo());

});
